const tk = '974d3f8fd3cba3f83d098b4220669a93'
const errorTileUrl = './imgs/gis/null.png'

export function init (dom) {
    const map = L.map(dom, {
        preferCanvas: true,
        positionControl: false,
        attributionControl: false,
        zoomControl: false,
        zoomSnap: window.devicePixelRatio > 1 ? 0.5 : 0.1,
        scrollWheelZoom: true,
        dragging: true,
        keyboard: false,
        touchZoom: true,
        doubleClickZoom: true,
        boxZoom: true,
        tap: true,
        maxBoundsViscosity: 1,
        zoom: 10,
        center: [25.87524527709376, 114.89366983570925]
    })
    L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${tk}`, {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        minZoom: 4,
        maxZoom: 18,
        maxNativeZoom: window.devicePixelRatio > 1 ? 17 : 18,
        detectRetina: true,
        errorTileUrl
    }).addTo(map)
    L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=${tk}`, {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        minZoom: 5,
        maxZoom: 18,
        maxNativeZoom: window.devicePixelRatio > 1 ? 17 : 18,
        detectRetina: true,
        errorTileUrl
    }).addTo(map)
    return map
}

export function getCurrLocation () {
    return new Promise((resolve) => {
        if (/localhost/.test(location.host)) {
            resolve({ status: true, latlng: [25.87524527709376, 114.89366983570925] })
        } else {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition((position) => {
                    const lat = position.coords.latitude
                    const lng = position.coords.longitude
                    resolve({ status: true, latlng: [lat, lng] })
                }, (error) => {
                    let msg = ''
                    if (error.code == error.PERMISSION_DENIED) {
                        msg = '定位失败,用户拒绝请求地理定位！'
                    } else if (error.code == error.POSITION_UNAVAILABLE) {
                        msg = '定位失败,位置信息是不可用！'
                    } else if (error.code == error.TIMEOUT) {
                        msg = '定位失败,请求获取用户位置超时！'
                    } else if (error.code == error.UNKNOWN_ERROR) {
                        msg = '定位失败！'
                    }
                    resolve({ status: false, msg })
                }, {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 30000
                })
            } else {
                resolve({ status: false, msg: '定位失败,用户已禁用位置获取权限！' })
            }
        }
    })
}

export function createMarker (map, latlng) {
    const icon = L.icon({ iconUrl: './imgs/gis/location.png', iconSize: [32, 32], iconAnchor: [16, 16] })
    return L.marker(latlng, { icon, draggable: true }).addTo(map)
}

export function getPlaceByLatlng (lat, lon) {
    const postStr = encodeURIComponent(JSON.stringify({ lon, lat, ver: 1 }))
    const url = `https://api.tianditu.gov.cn/geocoder?postStr=${postStr}&type=geocode&tk=${tk}`
    return fetch(url).then(res => res.json()).then(res => {
        if (res.msg == 'ok' && res.result) {
            return res.result.formatted_address
        } else {
            return '-'
        }
    })
}
